<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/10/18
 * Time: 4:00 PM
 */

namespace app\zyhsapi\model;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\zyhsapi\service\CacheZyhs;
use think\Log;
use traits\model\SoftDelete;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsUserCoupon extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_user_coupon';
    protected $cacheModel = 'user.coupon';
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    /**
     * 注册用户发送 新人福利
     * @param $uid
     * @param bool $isNew
     * @return void
     * @throws \RedisException
     */
    public function regUserSendBenefits($uid, bool $isNew = false)
    {
        if ($isNew || Util::CheckAppVersion('1.3.0') !== '小')
        {
            $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
            if (isset($testAccountConfig['register_send_benefits_type']) && $testAccountConfig['register_send_benefits_type'] == 2)
            {   // 赠送 新人福利
                (new ZyhsConsultRtcUserBenefits)->SaveData(1, $uid);
                //  添加缓存
                CacheZyhs::set('reg_user_send_benefits_' . $uid, 1, 86400);
                return;
            }
        }

        $nowTime = time();
        $endTime = strtotime('+7days', $nowTime);
        $data[] = [
            'type' => 2,
            'uid' => $uid,
            'c_id' => 733,
            'start_time' => $nowTime,
            'end_time' => $endTime,
            'give_time' => 0,
            'status' => 0,
            'is_give' => 0,
            'create_time' => $nowTime,
        ];
        $res = $this->add($uid, $data);
        if ($res === false)
        {
            Log::write('注册用户' . $uid . '赠送卡券失败', 'error', true);
        } else
        {
            CacheZyhs::set('reg_user_send_coupon_' . $uid, 1, 86400);
        }
    }

    /**
     * 获取 未使用的优惠券IDS
     * @param int $uid
     * @return int[]|
     * @throws \Exception
     */
    public function getCouponIds(int $uid)
    {
        $data = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage(-1)
            ->setSort('desc')
            ->setListKeyType(1)
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'status' => 0])->order('id desc')->column('id');
                    $resData = [];
                    foreach ($data as $v)
                    {
                        $resData[$v] = ['id' => $v];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    return [];
                }
            }, 'id', 0);

        return array_keys($data['data']);
    }

    /**
     * 获取卡卷数据
     * @param $uid int 用户id
     * @param $type int 1未使用 2已失效
     * @param bool $isPaging 是否分页
     * @return array|mixed
     * @throws \Exception
     */
    public function getList(int $uid, int $type, bool $isPaging = true)
    {
        $page = input('page', 1);
        if (!$isPaging)
        {
            $page = -1; // 获取所有数据
        }

        $sortKey = $type === 2 ? 'update_time' : 'id';

        $data = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize(10)
            ->setSort('desc')
            ->setListKeyType($type)
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid, $type)
            {
                return $this->getInfoByIdsInData($ids, [$uid, $type], $sortType);
            }, $sortKey, [], 0, 'list', 'list_details');

        $pageData = array_filter($data['data']);

        if (count($pageData) !== count($data['data']))
        {
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType($type)->rmCache('list');
        }
        $data['data'] = $this->dataInit($pageData);

        if (!$isPaging)
        {
            return $data['data'];
        }

        return $data;
    }


    /**
     * 获取信息
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $where = [];
            if ($ids)
            {
                $where['id'] = ['in', $ids];
            } else
            {
                $where['uid'] = $type[0];
                if ($type[1] === 1)
                {   // 未使用
                    $where['status'] = 0;
                    $this->order("id {$sortType}");
                } elseif ($type[1] === 2)
                {   // 已过期失效
                    $where['status'] = ['in', [1, 2, 3, 4]];
                    $this->order('update_time desc');
                }
            }
            $data = $this->where($where)->column('*', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'type', 'uid', 'c_id', 'start_time', 'end_time', 'give_time', 'status', 'is_give', 'rtc_id', 'create_time', 'update_time', 'delete_time']);
        }

        return $data;
    }


    /**
     * 优惠券领取
     * @param $uid
     * @param array $cData
     * @return bool
     * @throws \Exception
     */
    public function add($uid, array $cData): bool
    {
        try
        {
            $resData = $this->saveAll($cData);
            $ids = [];
            foreach ($resData as $item)
            {
                $ids[$item['id']] = $item['id'];
            }
        }
        catch (\Exception $e)
        {
            return false;
        }

        $this->listDataAdd($uid, $ids, 1); // 未使用
        return true;
    }

    /**
     * 优惠券使用和退回
     * @param $uid
     * @param $cid
     * @param $map
     * @return bool
     * @throws ApiException
     */
    public function use_return($uid, $cid, $map)
    {
        $couponInfo = $this->getInfoById($cid);

        if (empty($couponInfo) || $uid != $couponInfo['uid'])
        {   // 判断优惠券使用存在
            throw new ApiException('优惠券不存在');
        }

        try
        {
            $this->save($map, ['id' => $cid]);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $cid)->rmCache();
        }
        catch (\Exception $e)
        {
            throw new ApiException('服务异常');
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(1)->rmCache('list');
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(2)->rmCache('list');
        return true;
    }

    /**
     * 优惠券删除
     * @param int $uid
     * @param int $cid
     * @return bool
     * @throws \Exception
     */
    public function couponDel(int $uid, int $cid)
    {
        $couponInfo = $this->getInfoById($cid);

        if (empty($couponInfo) || $uid != $couponInfo['uid'])
        {   // 判断优惠券使用存在
            throw new ApiException('优惠券不存在');
        }
        try
        {
            self::destroy($cid); // 软删除

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $cid)->rmCache();
        }
        catch (\Exception $e)
        {
            throw new ApiException('服务异常');
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $cid)->rmCache();
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(1)->rmCache('list');
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(2)->rmCache('list');
        return true;
    }

    /**
     * 获取 本次连线 使用最佳的优惠券信息
     * @param int $uid
     * @param int $min 连线时长【分钟】
     * @return array | null
     * @throws \Exception
     */
    public function getConsultUseCouponInfo(int $uid, int $min)
    {
        $couponDatas = $this->getList($uid, 1, false);
        $zyhsCouponModel = new ZyhsCoupon();
        $resData = null;
        $nowTime = time();
        foreach ($couponDatas as $couponDataItem)
        {
            if ($couponDataItem['status'] > 0 || $nowTime >= $couponDataItem['end_time'])
            {   // 优惠券 已使用 或 已过期
                continue;
            }
            $couponAttrInfo = $zyhsCouponModel->getInfoById($couponDataItem['c_id']);
            if ($min >= $couponAttrInfo['condition'])
            {   // 是否符合满减条件
                if ($resData)
                {
                    if ($resData['discount'] > $couponAttrInfo['discount'])
                    {   // 满减时长 太小
                        continue;
                    } elseif ($resData['discount'] === $couponAttrInfo['discount'])
                    {   // 满减时长相同
                        if ($resData['condition'] > $couponAttrInfo['condition'])
                        {   // 满减条件 太小
                            continue;
                        } elseif ($resData['condition'] === $couponAttrInfo['condition'] && $resData['end_time'] <= $couponDataItem['end_time'])
                        {   // 满减条件 相同 且 过期时间更长或相同
                            continue;
                        }
                    }
                }

                $resData = [
                    'id' => $couponDataItem['id'],
                    'end_time' => $couponDataItem['end_time'],      // 过期时间
                    'condition' => $couponAttrInfo['condition'],    // 满减条件[分钟]
                    'discount' => $couponAttrInfo['discount'],      // 满减时长[分钟]
                ];
            }
        }

        return $resData;
    }
}
